package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.commons.result.UserLoginMsg;
import com.cskaoyan.order.biz.TransOutboundInvoker;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.factory.OrderProcessPipelineFactory;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.form.CreateOrderRequest;
import com.cskaoyan.order.service.OrderCoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

import static com.cskaoyan.order.constant.OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL;

@Slf4j
@Service
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;


    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Override
    public String createOrder(CreateOrderRequest request) {
        //创建pipeline对象
        TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

        //启动pipeline
        invoker.start(); //启动流程（pipeline来处理）

        //获取处理结果
        AbsTransHandlerContext context = invoker.getContext();

        //从Context中获取订单Id
        String orderId = context.getOrderId();
        return orderId;
    }

    @Override
    public void cancelOrder(String orderId, Long uid) {

        //校验
        Order order = orderMapper.selectByPrimaryKey(orderId);

        if (order.getUserId()!=uid){

            throw new ValidateException(SysRetCodeConstants.TOKEN_VALID_FAILED.getCode(),SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage());
        }else {

            //修改订单状态
            orderMapper.updateOrderStatus(ORDER_STATUS_TRANSACTION_CANCEL,orderId);

            //查找订单中商品
            List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);

            //订单中商品状态修改
            for (OrderItem orderItem : orderItems) {
                orderItemMapper.updateStockStatus(2,orderItem.getOrderId());

                //修改库存
                Stock stock = new Stock();
                stock.setLockCount(-orderItem.getNum());
                stock.setStockCount(Long.valueOf(orderItem.getNum()));
                stock.setItemId(orderItem.getItemId());
                stockMapper.updateStock(stock);

            }
        }

    }

    /**
     * 删除订单
     * @param orderId
     */
    @Override
    @Transactional
    public void deleteOrder(String orderId) {

        // 删除tb_order表中的订单
        orderMapper.deleteByPrimaryKey(orderId);

        // 删除tb_order_item表中的订单
        Example example = new Example(OrderShipping.class);
        example.createCriteria()
                .andEqualTo("orderId",orderId);
        orderItemMapper.deleteByExample(example);

        // 删除tb_order_shipping表中的订单
        orderShippingMapper.deleteByPrimaryKey(orderId);

    }

    @Override
    public void updateOrder(Integer status, String orderId) {
    }

}
